package com.example.xzs.admin.userlogin.config;

import com.alibaba.fastjson.JSON;
import com.example.xzs.admin.userlogin.JsoResult.JsonResult;
import com.example.xzs.admin.userlogin.enumerator.ServiceCode;
import com.example.xzs.admin.userlogin.filter.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Autowired
   private Jwt jwt;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

      http.addFilterBefore(jwt, UsernamePasswordAuthenticationFilter.class);
        // 允许跨域访问
        http.cors();

       http.exceptionHandling().authenticationEntryPoint((request, response, e) ->{
           log.debug("开始执行框架中的其他错误");
           String message="当前未登录，或登录信息已过期，请登录！";
           JsonResult jsonResult=JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED, message);
           String jsonResultString = JSON.toJSONString(jsonResult);
           response.setContentType("application/json; charset=utf-8");
           PrintWriter printWriter=response.getWriter();
           printWriter.println(jsonResultString);
           printWriter.close();
       } );



        String [] urls={
           "/api/student/user/register",
                "/api/user/login",
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/favicon.ico",
                "/test/simple-get",
                "/test/simple-post",
                "/passport/login",
        };


       http.csrf().disable();
       http.authorizeRequests()
               .mvcMatchers(urls)
               .permitAll()
               .anyRequest()
               .authenticated();

       // http.formLogin();
    }
}
